package com.qf.ademo;

import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

/**
 * 作者：熊剑
 * 时间：2023/11/1
 * 描述：
 */
/*使用java客户端向emqx服务器发送信息*/
public class PublishMessageDemo {

    public static void main(String[] args) throws MqttException {

        //1、实例化客户端
        int qos = 2;
        String broker = "tcp://43.143.125.148:1883";
        String clientId = "Java客户端的emqx_test";
        MemoryPersistence persistence = new MemoryPersistence();
        MqttClient client = new MqttClient(broker, clientId, persistence);

        //2、配置连接选项
        // MQTT 连接选项
        MqttConnectOptions connOpts = new MqttConnectOptions();
        connOpts.setUserName("qf");
        connOpts.setPassword("qf".toCharArray());
        // 保留会话
        connOpts.setCleanSession(true);

        //3、建立连接
        client.connect(connOpts);

        //4、发布消息
        MqttMessage message = new MqttMessage("hello".getBytes());
        message.setQos(qos);


        client.publish("topic", message);
    }

}
